/**
 * 聚划算
 * @author Jim
 * @date 2019/12/12
 * @update 2019/12/14
 */
import React, {PureComponent} from 'react';
import {FlatList, Image, StatusBar, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import ShopCard from '../../components/ShopCard';
import Axios from 'axios';
import {ActivityIndicator, Icon} from '@ant-design/react-native';
// import {
//   DefaultHeader,
//   SmartRefreshControl,
// } from 'react-native-smartrefreshlayout';
import {formatDate} from '../../utils/FormatDate';
import {get_allitem_list} from '../../api/haoDan';
import Navigation from '../../utils/Navigation';

// 初始化state
const default_state = {
    list: [],
    list_page: 1,
    list_loading: false,
    list_error: false,
    list_end: false,
};

export default class Filtrate extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            ...default_state,
            cid: this.props.navigation.state.params.cid,
            filtrate:  this.props.navigation.state.params.filtrate,
            sort: 'new',
            title:this.props.navigation.state.params.title,
        };
    }

    componentDidMount() {
        this.GetData();
    }

    componentWillUnmount = () => {
        this.setState = (state,callback)=>{
            return;
        };
    }

    getSort(sort) {
        switch (sort) {
            case 'new':
                return 1;
            case 'date_time':
                return 4;
            case 'total_sale_num_desc':
                return 3;
            case 'price_desc':
                return 8;
            case 'price_asc':
                return 9;
            default:
                return 0;
        }
    }

    /**
     * 获取数据
     */
    GetData() {
        const {
            filtrate,
            cid,
            sort,
            list,
            list_loading,
            list_end,
            list_page,
        } = this.state;
        if (list_loading && list_end) {
            return;
        }
        this.setState(
            {
                list_loading: true,
                list_error: false,
                list_end: false,
            },
            () => {
                get_allitem_list(cid, this.getSort(sort), list_page,filtrate)
                    .then((res) => {
                        this.setState({
                            list_loading: false,
                            list: list_page === 1 ? res.data : list.concat(res.data),
                            list_page: res.min_id,
                        });

                        this.rc && this.rc.finishRefresh();
                    })
                    .catch(() => {
                        this.setState({
                            list_loading: false,
                            list_error: true,
                        });
                    });
            },
        );
    }

    /**
     * 切换分类
     */
    ChangeSort(sort) {
        this.setState(
            {
                ...default_state,
                sort,
            },
            () => this.GetData(),
        );
    }

    render() {
        const {sort, list, list_end, list_error,title} = this.state;
        return (
            <View style={styles.container}>
                <View style={styles.header}>
                    <TouchableOpacity
                        activeOpacity={1}
                        style={styles.header_back}
                        onPress={() => Navigation.pop()}>
                        <Image source={require('../../images/back.png')} color={'#999999'} />
                    </TouchableOpacity>
                    <Text style={styles.header_body_text} numberOfLines={1}>
                        {title}
                    </Text>
                    <TouchableOpacity
                        activeOpacity={1}
                        style={styles.header_search}
                        onPress={() => Navigation.navigate('SearchIndex')}>
                        <Image
                            source={require('../../images/search_icon.png')}
                            style={styles.header_search_icon}
                        />
                    </TouchableOpacity>
                </View>
                <View style={styles.sort}>
                    <TouchableOpacity
                        activeOpacity={1}
                        style={styles.sort_item}
                        onPress={() => this.ChangeSort('new')}>
                        <Text
                            style={[
                                styles.sort_item_text,
                                sort === 'new' && {color: 'red', fontWeight: 'bold'},
                            ]}>
                            综合
                        </Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        activeOpacity={1}
                        style={styles.sort_item}
                        onPress={() => this.ChangeSort('date_time')}>
                        <Text
                            style={[
                                styles.sort_item_text,
                                sort === 'date_time' && {color: 'red', fontWeight: 'bold'},
                            ]}>
                            最新
                        </Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        activeOpacity={1}
                        style={styles.sort_item}
                        onPress={() => this.ChangeSort('total_sale_num_desc')}>
                        <Text
                            style={[
                                styles.sort_item_text,
                                sort === 'total_sale_num_desc' && {
                                    color: 'red',
                                    fontWeight: 'bold',
                                },
                            ]}>
                            销量
                        </Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        activeOpacity={1}
                        style={styles.sort_item}
                        onPress={() => {
                            if (sort === 'price_desc') {
                                this.ChangeSort('price_asc');
                            } else if (sort === 'price_asc') {
                                this.ChangeSort('price_desc');
                            } else {
                                this.ChangeSort('price_asc');
                            }
                        }}>
                        <Text
                            style={[
                                styles.sort_item_text,
                                (sort === 'price_asc' || sort === 'price_desc') && {
                                    color: 'red',
                                    fontWeight: 'bold',
                                },
                            ]}>
                            价格
                        </Text>
                        {sort === 'price_asc' ? (
                            <Image source={require('../../images/arrow-up.png')}  />
                        ) : sort === 'price_desc' ? (
                            <Image source={require('../../images/arrow-down.png')} />
                        ) : null}
                    </TouchableOpacity>
                </View>
                <FlatList
                    keyExtractor={(item) => item.productId}
                    data={list}
                    numColumns={2}
                    onEndReachedThreshold={0.2}
                    onEndReached={() => !list_end && !list_error && this.GetData()}
                    removeClippedSubviews
                    renderItem={(item) => <ShopCard item={item} />}
                    ListFooterComponent={
                        list_end ? (
                            <Text style={styles.list_footer}>已经到底了~</Text>
                        ) : list_error ? (
                            <Text style={styles.list_footer}>网络有点问题~</Text>
                        ) : (
                            <View style={{height: 30, justifyContent: 'center'}}>
                                <ActivityIndicator color={'#F55C6E'} text={'加载中'} />
                            </View>
                        )
                    }
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {flex: 1, backgroundColor: '#F4F4F4'},
    sort: {
        zIndex: 10,
        flexDirection: 'row',
        backgroundColor: '#fff',
    },
    sort_item: {
        flex: 1,
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
    },
    sort_item_text: {
        color: '#000',
    },
    list_footer: {
        textAlign: 'center',
        height: 30,
        lineHeight: 30,
    },
    header: {
        height: 36,
        flexDirection: 'row',
        marginTop: StatusBar.currentHeight + 5,
        marginBottom: 5,
        justifyContent: 'center',
        alignItems: 'center',
    },
    header_back: {
        marginLeft: 15,
        marginRight: 5,
    },
    header_body: {
        flex: 1,
        height: 36,
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#fff',
        borderRadius: 5,
        marginRight: 10,
    },
    header_body_text: {
        flex: 1,
        fontSize: 18,
        fontWeight: 'bold',
        paddingLeft: 10,
    },
    header_search: {
        justifyContent: 'center',
        alignItems: 'center',
        paddingHorizontal: 15,
    },
    header_search_icon: {
        width: 24,
        height: 24,
        tintColor: '#000',
    },
});
